package com.ai.bitcoin.contrab;


import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;


/**
 * 
 * @author xd
 *
 */
public final class QuartzTaskManager {
	
	public static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
	
	

	
	/**
	 * 
	 * @param jobName
	 * @param cls
	 * @param time
	 * @throws Exception
	 */
	@SuppressWarnings("all")
	public static void addJob(String jobName, Class cls, String time) throws Exception {
		Scheduler sched = gSchedulerFactory.getScheduler();
		JobDetail jobDetail = new JobDetail(jobName, getJobName(jobName), cls);
		CronTrigger trigger = new CronTrigger(jobName, getTriggerName(jobName));
		trigger.setCronExpression(time);
		sched.scheduleJob(jobDetail, trigger);
		if (!sched.isShutdown()) {
			sched.start();
		}
	}

	/**
	 * 
	 * @param jobName
	 * @throws Exception
	 */
	public static void removeJob(String jobName) throws Exception {
		Scheduler sched = gSchedulerFactory.getScheduler();
		sched.pauseTrigger(jobName, getTriggerName(jobName));
		sched.unscheduleJob(jobName, getTriggerName(jobName));
		sched.deleteJob(jobName, getJobName(jobName));
	}
	
//	/**
//	 * 获取所有任务的名称
//	 * 
//	 * @return
//	 * @throws Exception
//	 */
//	public static JSONObject getAllJob() throws Exception {
//		JSONObject json = new JSONObject();
//		List<String> jobNameList = new ArrayList<String>();
//		List<String> triggerNameList = new ArrayList<String>();
//		Scheduler sched = gSchedulerFactory.getScheduler();
//		String[] groupNames = sched.getJobGroupNames();
//		for (int i = 0; i < groupNames.length; i++) {
//			jobNameList.add(groupNames[i]);
//		}
//		String[] triggerNames = sched.getTriggerGroupNames();
//		for (int i = 0; i < triggerNames.length; i++) {
//			triggerNameList.add(triggerNames[i]);
//		}
//		json.put("jobNameList", jobNameList);
//		json.put("triggerNameList", triggerNameList);
//		return json;
//	}


	/**
	 * 
	 * @param name
	 * @return
	 */
	public static String getJobName(String name) {
		return "job_" + name;
	}

	/**
	 * 
	 * @param name
	 * @return
	 */
	public static String getTriggerName(String name) {
		return "trigger_" + name;
	}

}
